var express = require('express');
fs = require('fs');
db = require('../db/db.js');

var router = express.Router();

router.get('/', function (req, res) {
    res.render('index',{
        title:'我图网主页'
    })
});
// 注册
router.post('/api/register',function(req,res){
    var user = {};
    user.name = req.body.name;
    user.password = req.body.password1;
    console.log(user)
    db.User.find({name:user.name}, function (err, data) {
        if(!err){
            if(data.length>0){
                res.status(200).json({ "code": "error", "content": "对不起，此用户名被占用" })
            }else{
                new db.User(user).save(function (err) {
                    if (!err) {
                        res.status(200).json({ "code": "success", "content": "恭喜，" + user.name + "注册成功" });
                    }
                })
            }
        }
    })
});

// 登录
router.post('/api/login', function (req, res) {
    var user = req.body;
    user.name=req.body.name;
    user.password=req.body.password;
    db.User.find({name:user.name,password:user.password}, function (err, data) {
        if(!err){
            if(data.length>0){
                console.log(data);
                res.status(200).json({"code":"success","content":"欢迎您，"+user.name,data:data});
            }else{
                res.status(200).json({"code":"error","content":"对不起账号密码错误，请确认后重新输入"});
            }
        }
    })
})

module.exports = router;